万恶的算法作业,要找寻一条边是否在MST中,看似简单,却暗藏玄机,因为一个graph可能不止有一个MST,用Kruskal 算法找到MST固然简单,但找到所有MST似乎就只能用Prim了。不想删掉我辛辛苦苦写的Kruskal算法,便写了这篇文章作为总结。
题目
[python3] (7 points) Devise, then code in python 3, a efficient algorithm for the following problem. Inputs: (i) a connected weighted undirected graph G = ⟨V,E⟩, and, (ii) an edge e ∈ E. Output: true if there is a minimum spanning tree of G that contains e, and false otherwise. G is provided in adjacency list format, and e as a list which encodes a pair. E.g., an encoding of the following graph is [[[3,10], [1,100], [2, 20]], [[0,100]], [[0,20],[3,10]], [[2,10],[0,10]]], and the output is false for edge [2,0] and true for edge [0,1].
- Kruskal
1 | def mstexists(G, e): |
- Prim
用于寻找所有的 MST 所包含的边。
1 | def mstexists(G, e): |
亮点:1. 使用sorted避免加入重复边。